package com.zhongwang.mms.module.basic.service;

import com.zhongwang.mms.gen.entity.*;
import com.zhongwang.mms.module.basic.dao.MMaterialDictionaryDao;
import com.zhongwang.mms.module.basic.dao.MMaterialsDao;
import com.zhongwang.mms.module.basic.dao.TWarehouseInfoDao;
import com.zhongwang.mms.module.basic.model.MMaterialsModel;
import com.zhongwang.mms.module.material.dao.MInventoryDao;
import com.zhongwang.mms.module.material.dao.MOrderDetailDao;
import com.zhongwang.mms.module.material.model.ImportMaterialModel;
import com.zhongwang.mms.module.system.log.LogService;
import com.zhongwang.mms.util.ShiroUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import static com.zhongwang.mms.util.PoiUtils.getValue;
import static com.zhongwang.mms.util.StringUtils.isNumber;


/**
 * @Description: 添加原料数据字典 服务层
 * @Author: China.wsg
 * @Date: 2020/03/16 11:23
 */
@Service
public class MMaterialsService {

    @Autowired
    private LogService logService;
    @Autowired
    private MMaterialsDao mMaterialsDao;
    @Autowired
    private MMaterialDictionaryDao mMaterialDictionaryDao;
    @Autowired
    private MInventoryDao mInventoryDao;
    @Autowired
    private MOrderDetailDao mOrderDetailDao;
    @Autowired
    private TWarehouseInfoDao warehouseInfoDao;
    @Autowired
    private MMaterialDictionaryService materialDictionaryService;

    @Value("${user.upload.path}")
    private String uploadPath;

    /**
     * 获取库位信息（仓位名称升序）
     *
     * @return
     */
    public List<TWarehouseInfo> findMaterialStockByOrderByStockNameAsc(String whiName) {

        TWarehouseInfoExample ex = new TWarehouseInfoExample();
        ex.setOrderByClause("whi_name asc");
        TWarehouseInfoExample.Criteria criteria = ex.createCriteria();

        // 状态：1 可用
        criteria.andWhiStatusEqualTo(1);
        criteria.andWhiTypeEqualTo("原料库位");
        if (whiName != null && whiName != "") {
            criteria.andWhiNameEqualTo(whiName);
        }
        return warehouseInfoDao.selectByExample(ex);
    }

    /**
     * 根据条件获取重量公式
     *
     * @param matTypeId 类型Id
     * @return
     */
    public Integer getFormulaType(Integer matTypeId) {

        MMaterialDictionary materialDictionary = mMaterialDictionaryDao.selectByPrimaryKey(matTypeId);
        return materialDictionary.getMdFormulaType();
    }

    /**
     * 保存原料基础信息
     *
     * @param materials 保存信息
     * @return
     */
    public String saveMaterials(MMaterials materials) {

        // 原料名称拼接取得
        String typeName = mMaterialDictionaryDao.selectByPrimaryKey(materials.getMatTypeId()).getMdName();
        String qualityName = mMaterialDictionaryDao.selectByPrimaryKey(materials.getMatQualityId()).getMdName();
        String specName = mMaterialDictionaryDao.selectByPrimaryKey(materials.getMatSpecId()).getMdName();

        String materialDesc = typeName + "_" + qualityName + "_" + specName + "  " + materials.getMatWidth() + "*" + materials.getMatLength() + "*" + materials.getMatHeight();

        // 原料名称不允许重复
        MMaterialsExample ex = new MMaterialsExample();
        MMaterialsExample.Criteria criteria = ex.createCriteria();

        criteria.andMatTypeIdEqualTo(materials.getMatTypeId());
        criteria.andMatQualityIdEqualTo(materials.getMatQualityId());
        criteria.andMatSpecIdEqualTo(materials.getMatSpecId());
        criteria.andMatStatusEqualTo(1);
        if (materials.getMatWidth() != null) {
            criteria.andMatWidthEqualTo(materials.getMatWidth());
        } else {
            criteria.andMatWidthIsNull();
        }
        if (materials.getMatLength() != null) {
            criteria.andMatLengthEqualTo(materials.getMatLength());
        } else {
            criteria.andMatLengthIsNull();
        }
        if (materials.getMatHeight() != null) {
            criteria.andMatHeightEqualTo(materials.getMatHeight());
        } else {
            criteria.andMatHeightIsNull();
        }

        List<MMaterials> materialsList = mMaterialsDao.selectByExample(ex);

        if (materialsList != null && materialsList.size() > 0) {
            return "原料：" + materialDesc + "在系统中已存在，保存失败！";
        }

        // 原料编码生成规则：类型+材质+规格+0001（四位流水）
        String typeCode = mMaterialDictionaryDao.selectByPrimaryKey(materials.getMatTypeId()).getMdMatCode();
        String qualityCode = mMaterialDictionaryDao.selectByPrimaryKey(materials.getMatQualityId()).getMdMatCode();
        String specCode = mMaterialDictionaryDao.selectByPrimaryKey(materials.getMatSpecId()).getMdMatCode();

        String materialCode;
        String maxMaterialBaseCode;

        ex.clear();
        ex = new MMaterialsExample();
        ex.setOrderByClause("mat_code desc");
        criteria = ex.createCriteria();
        criteria.andMatCodeLike(typeCode + qualityCode + specCode + "%");
        List<MMaterials> mMaterials = mMaterialsDao.selectByExample(ex);

        if (mMaterials != null && mMaterials.size() > 0) {
            maxMaterialBaseCode = mMaterials.get(0).getMatCode();
            materialCode = typeCode + qualityCode + specCode + String.format("%0" + 4 + "d", Integer.parseInt(maxMaterialBaseCode.substring(maxMaterialBaseCode.length() - 4, maxMaterialBaseCode.length())) + 1);
        } else {
            materialCode = typeCode + qualityCode + specCode + "0001";
        }

        materials.setMatCode(materialCode);
        materials.setMatNameDesc(materialDesc);
        materials.setMatStatus(1);

        logService.saveLog("创建原料名称", materialDesc);
        mMaterialsDao.insertSelective(materials);
        return "";

    }

    /**
     * 原料基础列表
     *
     * @param materialsModel 查询条件
     * @return 原料基础列表
     */
    public List<MMaterialsModel> findMaterialsModelByQuery(MMaterialsModel materialsModel) {
        return mMaterialsDao.findMaterialsModelByQuery(materialsModel);
    }

    /**
     * 删除原料基础数据
     *
     * @param materials 被删除数据
     * @return
     */
    public String delMMaterials(MMaterials materials) {

        // 判断：如果原料被单据（入库单、串料申请单、在库明细）使用，不允许删除
        Boolean boolCheckUsedBill = CheckUsedBillMessage(materials.getMatId());
        if (boolCheckUsedBill == false) {
            return "此商品存在出入库单据，不能变动！";
        }

        MMaterials mMaterials = mMaterialsDao.selectByPrimaryKey(materials.getMatId());

        logService.saveLog("删除原料名称：", mMaterials.getMatNameDesc());
        mMaterials.setMatStatus(0);
        mMaterialsDao.updateByPrimaryKey(mMaterials);
        return "";
    }

    /**
     * 判断原料是否被单据使用
     *
     * @param id
     * @return
     */
    private Boolean CheckUsedBillMessage(Integer id) {

        // 判断：如果原料被单据（入库单、在库明细）使用，不允许删除

        // 在库明细
        MInventoryExample ex = new MInventoryExample();
        MInventoryExample.Criteria criteria = ex.createCriteria();
        criteria.andItyMatIdEqualTo(id);
        criteria.andItyNumGreaterThan(0d);
        criteria.andItyAvaNumGreaterThan(0d);
        Long inventoryCount = mInventoryDao.countByExample(ex);

        if (inventoryCount > 0) {
            return false;
        }

        // 入库单
        MOrderDetailExample ex1 = new MOrderDetailExample();
        MOrderDetailExample.Criteria criteria1 = ex1.createCriteria();
        criteria1.andOdaMatIdEqualTo(id);
        criteria1.andOdaRedFlagNotEqualTo(2);
        Long orderDetailCount = mOrderDetailDao.countByExample(ex1);

        if (orderDetailCount > 0) {
            return false;
        }
        return true;
    }

    /**
     * 修改原料物料数据字典
     *
     * @param newMaterial 修改内容
     * @return
     */
    public String updateMaterials(MMaterials newMaterial) {

        // 新原料名称拼接取得
        String typeName = mMaterialDictionaryDao.selectByPrimaryKey(newMaterial.getMatTypeId()).getMdName();
        String qualityName = mMaterialDictionaryDao.selectByPrimaryKey(newMaterial.getMatQualityId()).getMdName();
        String specName = mMaterialDictionaryDao.selectByPrimaryKey(newMaterial.getMatSpecId()).getMdName();

        String newMaterialName = typeName + "_" + qualityName + "_" + specName + "  " + newMaterial.getMatWidth() + "*" + newMaterial.getMatLength() + "*" + newMaterial.getMatHeight();

        MMaterials oldMaterials = mMaterialsDao.selectByPrimaryKey(newMaterial.getMatId());

        // 判断：如果原料被单据（入库单、串料申请单、在库明细）使用，不允许删除
        Boolean boolCheckUsedBill = CheckUsedBillMessage(newMaterial.getMatId());

        if (boolCheckUsedBill == false) {

            Double newWidth = newMaterial.getMatWidth() == null ? 0 : newMaterial.getMatWidth();
            Double oldWidth = oldMaterials.getMatWidth() == null ? 0 : oldMaterials.getMatWidth();
            Double newLength = newMaterial.getMatLength() == null ? 0 : newMaterial.getMatLength();
            Double oldLength = oldMaterials.getMatLength() == null ? 0 : oldMaterials.getMatLength();
            Double newHeight = newMaterial.getMatHeight() == null ? 0 : newMaterial.getMatHeight();
            Double oldHeight = oldMaterials.getMatHeight() == null ? 0 : oldMaterials.getMatHeight();

            /*判断本次修改内容：如果修改内容为类型、材质、规格、宽、长、厚，则不允许修改。
                              如果修改内容为分类、单位、公式、仓位等信息，则允许修改。*/
            if (newMaterial.getMatTypeId() != oldMaterials.getMatTypeId()
                    || newMaterial.getMatQualityId() != oldMaterials.getMatQualityId()
                    || newMaterial.getMatSpecId() != oldMaterials.getMatSpecId()
                    || newWidth.compareTo(oldWidth) != 0 || newLength.compareTo(oldLength) != 0 || newHeight.compareTo(oldHeight) != 0) {
                return "此商品存在出入库单据，不能变动！";
            }
        }

        // 原料名称不允许重复
        MMaterialsExample ex = new MMaterialsExample();
        MMaterialsExample.Criteria criteria = ex.createCriteria();

        criteria.andMatTypeIdEqualTo(newMaterial.getMatTypeId());
        criteria.andMatQualityIdEqualTo(newMaterial.getMatQualityId());
        criteria.andMatSpecIdEqualTo(newMaterial.getMatSpecId());
        if (newMaterial.getMatWidth() != null) {
            criteria.andMatWidthEqualTo(newMaterial.getMatWidth());
        } else {
            criteria.andMatWidthIsNull();
        }
        if (newMaterial.getMatLength() != null) {
            criteria.andMatLengthEqualTo(newMaterial.getMatLength());
        } else {
            criteria.andMatLengthIsNull();
        }
        if (newMaterial.getMatHeight() != null) {
            criteria.andMatHeightEqualTo(newMaterial.getMatHeight());
        } else {
            criteria.andMatHeightIsNull();
        }
        criteria.andMatIdNotEqualTo(newMaterial.getMatId());

        List<MMaterials> materialByAll = mMaterialsDao.selectByExample(ex);
        if (materialByAll != null && materialByAll.size() > 0) {
            return "原料：" + newMaterialName + "在系统中已存在，保存失败！";
        }

        // 原料编码生成规则：类型+材质+规格+0001（四位流水）
        String typeCode = mMaterialDictionaryDao.selectByPrimaryKey(newMaterial.getMatTypeId()).getMdMatCode();
        String qualityCode = mMaterialDictionaryDao.selectByPrimaryKey(newMaterial.getMatQualityId()).getMdMatCode();
        String specCode = mMaterialDictionaryDao.selectByPrimaryKey(newMaterial.getMatSpecId()).getMdMatCode();

        String materialCode;
        String maxMaterialBaseCode;

        ex.clear();
        ex = new MMaterialsExample();
        ex.setOrderByClause("mat_code desc");
        criteria = ex.createCriteria();
        criteria.andMatCodeLike(typeCode + qualityCode + specCode + "%");
        List<MMaterials> mMaterials = mMaterialsDao.selectByExample(ex);

        if (mMaterials != null && mMaterials.size() > 0) {
            maxMaterialBaseCode = mMaterials.get(0).getMatCode();
            materialCode = typeCode + qualityCode + specCode + String.format("%0" + 4 + "d", Integer.parseInt(maxMaterialBaseCode.substring(maxMaterialBaseCode.length() - 4, maxMaterialBaseCode.length())) + 1);
        } else {
            materialCode = typeCode + qualityCode + specCode + "0001";
        }

        newMaterial.setMatCode(materialCode);
        newMaterial.setMatNameDesc(newMaterialName);
        newMaterial.setMatStatus(1);

        newMaterial.setMatCode(materialCode);

        logService.saveLog("修改原料信息", oldMaterials, newMaterial);
        mMaterialsDao.updateByPrimaryKey(newMaterial);
        return "";
    }

    /**
     * 判断文件是否存在
     *
     * @param url 文件URL
     * @return 是否存在
     */
    public boolean exist(String url) {
        int i = url.lastIndexOf("files/");
        String path = uploadPath + url.substring(i + 6);
        File file = new File(path);
        if (!file.exists()) {
            return false;
        }
        return true;
    }

    /**
     * 导入物料
     *
     * @param file 导入文件
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public String importFile(MultipartFile file) {

        String fileName = file.getOriginalFilename();
        MMaterials importMaterial;// 待导入物料
        int importCount = 0; // 导入物料结果

        // 错误数据
        List<ImportMaterialModel> errorList = new ArrayList<>();
        Workbook workbook = null;
        try {
            // 判断文件是2007版本还是2010版本
            InputStream is = file.getInputStream();
            if (fileName.endsWith("xlsx")) {
                workbook = new XSSFWorkbook(is);
            }
            if (fileName.endsWith("xls")) {
                workbook = new HSSFWorkbook(is);
            }
            if (workbook != null) {
                //默认读取第一个sheet
                Sheet sheet = workbook.getSheetAt(0);
                ImportMaterialModel importMaterialModel;
                // 排除标题行，从第二行开始导入
                for (int i = sheet.getFirstRowNum() + 1; i <= sheet.getLastRowNum(); i++) {
                    Row row = sheet.getRow(i);
                    // 如果行为空忽略
                    if (row == null) {
                        continue;
                    }
                    /** Excel待导入数据获取*/
                    importMaterialModel = new ImportMaterialModel();
                    importMaterialModel.setMaterialKind(getValue(row.getCell(0)));
                    importMaterialModel.setMatTypeName(getValue(row.getCell(1)));
                    importMaterialModel.setMatQualityName(getValue(row.getCell(2)));
                    importMaterialModel.setMatSpecName(getValue(row.getCell(3)));
                    if (importMaterialModel.getMaterialKind() == null && importMaterialModel.getMatTypeName() == null
                            && importMaterialModel.getMatQualityName() == null && importMaterialModel.getMatSpecName() == null) {
                        continue;
                    }
                    // 宽
                    if (row.getCell(4) != null && row.getCell(4).getCellType() == CellType.NUMERIC) {
                        importMaterialModel.setMatWidth(String.valueOf(row.getCell(4).getNumericCellValue()));
                    } else {
                        importMaterialModel.setMatWidth(getValue(row.getCell(4)));
                    }
                    // 长
                    if (row.getCell(5) != null && row.getCell(5).getCellType() == CellType.NUMERIC) {
                        importMaterialModel.setMatLength(String.valueOf(row.getCell(5).getNumericCellValue()));
                    } else {
                        importMaterialModel.setMatLength(getValue(row.getCell(5)));
                    }
                    // 高
                    if (row.getCell(6) != null && row.getCell(6).getCellType() == CellType.NUMERIC) {
                        importMaterialModel.setMatHeight(String.valueOf(row.getCell(6).getNumericCellValue()));
                    } else {
                        importMaterialModel.setMatHeight(getValue(row.getCell(6)));
                    }
                    importMaterialModel.setMatStock(getValue(row.getCell(7)));
                    importMaterialModel.setMatNumUnit(getValue(row.getCell(8)));
                    importMaterialModel.setMatWeightUnit(getValue(row.getCell(9)));
                    importMaterialModel.setMatSapNameDesc(getValue(row.getCell(10)));

                    /** 数据有效性判断*/
                    // 判断：分类、类型、材质、规格必填
                    if (StringUtils.isEmpty(importMaterialModel.getMaterialKind()) || StringUtils.isEmpty(importMaterialModel.getMatTypeName())
                            || StringUtils.isEmpty(importMaterialModel.getMatQualityName()) || StringUtils.isEmpty(importMaterialModel.getMatSpecName())) {
                        importMaterialModel.setErrorReason("必填字段为空");
                        errorList.add(importMaterialModel);
                        continue;
                    }
                    // 判断：宽、长、高字段都是数值格式
                    if (!StringUtils.isEmpty(importMaterialModel.getMatWidth()) && !isNumber(importMaterialModel.getMatWidth())) {
                        importMaterialModel.setErrorReason("[宽度]字段应该为数字格式，不应含有英文或汉字");
                        errorList.add(importMaterialModel);
                        continue;
                    }
                    if (!StringUtils.isEmpty(importMaterialModel.getMatLength()) && !isNumber(importMaterialModel.getMatLength())) {
                        importMaterialModel.setErrorReason("[长度]字段应该为数字格式，不应含有英文或汉字");
                        errorList.add(importMaterialModel);
                        continue;
                    }
                    if (!StringUtils.isEmpty(importMaterialModel.getMatHeight()) && !isNumber(importMaterialModel.getMatHeight())) {
                        importMaterialModel.setErrorReason("[高度]字段应该为数字格式，不应含有英文或汉字");
                        errorList.add(importMaterialModel);
                        continue;
                    }
                    // 判断：分类必须为‘型材’和 ‘板材’
                    if (!"型材".equals(importMaterialModel.getMaterialKind()) && !"板材".equals(importMaterialModel.getMaterialKind())) {
                        importMaterialModel.setErrorReason("[分类]字段应该为‘型材’或‘板材’");
                        errorList.add(importMaterialModel);
                        continue;
                    }
                    // 判断：类型必须在数据库中存在
                    List<MMaterialDictionary> matTypeList = getMaterialDictionary("类型", importMaterialModel);
                    if (matTypeList.size() == 0) {
                        importMaterialModel.setErrorReason("类型：" + importMaterialModel.getMatTypeName() + "，在系统中不存在，请先维护到系统中");
                        errorList.add(importMaterialModel);
                        continue;
                    }
                    // 判断：区位必须在数据库中存在
                    List<TWarehouseInfo> warehouseInfos = new ArrayList<>();
                    if (importMaterialModel.getMatStock() != null && !StringUtils.isEmpty(importMaterialModel.getMatStock())) {
                        warehouseInfos = findMaterialStockByOrderByStockNameAsc(importMaterialModel.getMatStock());
                        if (warehouseInfos.size() == 0) {
                            importMaterialModel.setErrorReason("区位：" + importMaterialModel.getMatStock() + "，在系统中不存在，请先维护到系统中");
                            errorList.add(importMaterialModel);
                            continue;
                        }
                    }

                    /** 插入物料信息*/
                    importMaterial = new MMaterials();
                    importMaterial.setMatHeight((StringUtils.isEmpty(importMaterialModel.getMatHeight()) || importMaterialModel.getMatHeight() == null) ? null : Double.valueOf(importMaterialModel.getMatHeight()));
                    importMaterial.setMatLength((StringUtils.isEmpty(importMaterialModel.getMatLength()) || importMaterialModel.getMatLength() == null) ? null : Double.valueOf(importMaterialModel.getMatLength()));
                    importMaterial.setMatWidth((StringUtils.isEmpty(importMaterialModel.getMatWidth()) || importMaterialModel.getMatWidth() == null) ? null : Double.valueOf(importMaterialModel.getMatWidth()));
                    importMaterial.setMatStatus(1);
                    importMaterial.setMatNumUnit(importMaterialModel.getMatNumUnit());
                    importMaterial.setMatWeightUnit(importMaterialModel.getMatWeightUnit());
                    importMaterial.setMaterialKind(importMaterialModel.getMaterialKind());
                    importMaterial.setMatFormulaType(matTypeList.get(0).getMdFormulaType());
                    importMaterial.setMatTypeId(matTypeList.get(0).getMdId());
                    // 材质
                    List<MMaterialDictionary> matQualityList = getMaterialDictionary("材质", importMaterialModel);
                    String qualityCode;
                    if (matQualityList.size() == 0) {
                        // 插入材质
                        MMaterialDictionary qualityDic = new MMaterialDictionary();
                        qualityDic.setMdMatCode(materialDictionaryService.getMaterialCode(2000));
                        qualityDic.setMdName(importMaterialModel.getMatQualityName());
                        qualityDic.setMdPid("板材".equals(importMaterialModel.getMaterialKind()) ? 1 : 2);
                        qualityDic.setMdStatus(1);
                        qualityDic.setMdTypeNum(2000);
                        mMaterialDictionaryDao.insert(qualityDic);
                        importMaterial.setMatQualityId(qualityDic.getMdId());
                        qualityCode = qualityDic.getMdMatCode();
                    } else {
                        importMaterial.setMatQualityId(matQualityList.get(0).getMdId());
                        qualityCode = matQualityList.get(0).getMdMatCode();
                    }
                    // 规格
                    List<MMaterialDictionary> matSpecList = getMaterialDictionary("规格", importMaterialModel);
                    String specCode;
                    if (matSpecList.size() == 0) {
                        // 插入规格
                        MMaterialDictionary specDic = new MMaterialDictionary();
                        specDic.setMdMatCode(materialDictionaryService.getMaterialCode(3000));
                        specDic.setMdName(importMaterialModel.getMatSpecName());
                        specDic.setMdPid("板材".equals(importMaterialModel.getMaterialKind()) ? 1 : 2);
                        specDic.setMdStatus(1);
                        specDic.setMdTypeNum(3000);
                        mMaterialDictionaryDao.insert(specDic);
                        importMaterial.setMatSpecId(specDic.getMdId());
                        specCode = specDic.getMdMatCode();
                    } else {
                        importMaterial.setMatSpecId(matSpecList.get(0).getMdId());
                        specCode = matSpecList.get(0).getMdMatCode();
                    }

                    /** 判断：物料已经存在不允许保存 */
                    MMaterialsExample ex = new MMaterialsExample();
                    MMaterialsExample.Criteria criteria = ex.createCriteria();
                    criteria.andMatTypeIdEqualTo(importMaterial.getMatTypeId());
                    criteria.andMatQualityIdEqualTo(importMaterial.getMatQualityId());
                    criteria.andMatSpecIdEqualTo(importMaterial.getMatSpecId());
                    criteria.andMatStatusEqualTo(1);
                    if (importMaterial.getMatWidth() != null) {
                        criteria.andMatWidthEqualTo(importMaterial.getMatWidth());
                    } else {
                        criteria.andMatWidthIsNull();
                    }
                    if (importMaterial.getMatLength() != null) {
                        criteria.andMatLengthEqualTo(importMaterial.getMatLength());
                    } else {
                        criteria.andMatLengthIsNull();
                    }
                    if (importMaterial.getMatHeight() != null) {
                        criteria.andMatHeightEqualTo(importMaterial.getMatHeight());
                    } else {
                        criteria.andMatHeightIsNull();
                    }
                    List<MMaterials> materialsList = mMaterialsDao.selectByExample(ex);
                    if (materialsList != null && materialsList.size() > 0) {
                        importMaterialModel.setErrorReason("原料在系统中已存在，保存失败");
                        errorList.add(importMaterialModel);
                        continue;
                    }
                    if (importMaterialModel.getMatStock() != null && !StringUtils.isEmpty(importMaterialModel.getMatStock())) {
                        importMaterial.setMatStockId(warehouseInfos.get(0).getWhiId());
                    }
                    importMaterial.setMatSapNameDesc(importMaterialModel.getMatSapNameDesc());
                    /** 物料编码 */
                    // 原料编码生成规则：类型+材质+规格+0001（四位流水）
                    String typeCode = matTypeList.get(0).getMdMatCode();
                    String materialCode;
                    String maxMaterialBaseCode;
                    ex.clear();
                    ex = new MMaterialsExample();
                    ex.setOrderByClause("mat_code desc");
                    criteria = ex.createCriteria();
                    criteria.andMatCodeLike(typeCode + qualityCode + specCode + "%");
                    List<MMaterials> mMaterials = mMaterialsDao.selectByExample(ex);
                    if (mMaterials != null && mMaterials.size() > 0) {
                        maxMaterialBaseCode = mMaterials.get(0).getMatCode();
                        materialCode = typeCode + qualityCode + specCode + String.format("%0" + 4 + "d", Integer.parseInt(maxMaterialBaseCode.substring(maxMaterialBaseCode.length() - 4, maxMaterialBaseCode.length())) + 1);
                    } else {
                        materialCode = typeCode + qualityCode + specCode + "0001";
                    }
                    importMaterial.setMatCode(materialCode);
                    // 物料描述
                    String materialDesc = importMaterialModel.getMatTypeName() + "_" + importMaterialModel.getMatQualityName() + "_" + importMaterialModel.getMatSpecName()
                            + "  " + importMaterial.getMatWidth() + "*" + importMaterial.getMatLength() + "*" + importMaterial.getMatHeight();
                    importMaterial.setMatNameDesc(materialDesc);

                    /** 物料保存 */
                    mMaterialsDao.insertSelective(importMaterial);
                    importCount++;
                }

                // 保存导入失败数据
                // 创建HSSFWorkbook对象(excel的文档对象)
                HSSFWorkbook wb = new HSSFWorkbook();
                // 建立新的sheet对象（excel的表单）
                HSSFSheet hssfSheet = wb.createSheet("sheet1");
                // 在sheet里创建第一行，参数为行索引(excel的行)，可以是0～65535之间的任何一个
                HSSFRow hssfRow = hssfSheet.createRow(0);
                // 创建单元格（excel的单元格，参数为列索引，可以是0～255之间的任何一个
                HSSFCell hssfCell = hssfRow.createCell(0);
                // 设置单元格内容
                hssfCell.setCellValue("导入失败数据" + DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
                // 合并单元格CellRangeAddress构造参数依次表示起始行，截至行，起始列， 截至列
                hssfSheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 11));
                // 在sheet里创建第二行
                for (int i = 0; i < errorList.size(); i++) {
                    HSSFRow row = hssfSheet.createRow(i + 1);
                    row.createCell(0).setCellValue(errorList.get(i).getMaterialKind());
                    row.createCell(1).setCellValue(errorList.get(i).getMatTypeName());
                    row.createCell(2).setCellValue(errorList.get(i).getMatQualityName());
                    row.createCell(3).setCellValue(errorList.get(i).getMatSpecName());
                    row.createCell(4).setCellValue(errorList.get(i).getMatWidth());
                    row.createCell(5).setCellValue(errorList.get(i).getMatLength());
                    row.createCell(6).setCellValue(errorList.get(i).getMatHeight());
                    row.createCell(7).setCellValue(errorList.get(i).getMatStock());
                    row.createCell(8).setCellValue(errorList.get(i).getMatNumUnit());
                    row.createCell(9).setCellValue(errorList.get(i).getMatWeightUnit());
                    row.createCell(10).setCellValue(errorList.get(i).getMatSapNameDesc());
                    row.createCell(11).setCellValue(errorList.get(i).getErrorReason());
                }

                // 保存文件到固定路径
                String path = uploadPath + ShiroUtils.getUser().getAccount() + "/";
                File dir = new File(path);
                if (!dir.exists()) {
                    dir.mkdirs();
                }
                File saveFile = new File(path + "error.xls");
                FileOutputStream output = new FileOutputStream(saveFile);
                wb.write(output);//写入磁盘
                output.close();
                logService.saveLog("原料物料信息导入", "导入成功：" + importCount + "条， " + "导入失败：" + errorList.size() + "条");
                return errorList.size() > 0 ? "导入失败" : "导入完成";
            } else {
                return "导入失败";
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (workbook != null) {
                try {
                    workbook.close();
                } catch (Exception ignored) {
                }
            }
        }
        return "导入失败";
    }

    /**
     * 判断物料类型是否存在
     * @param matKind 分类
     * @param matType 类型
     */

    /**
     * 判断原料数据字典是否存在
     *
     * @param matType     类型区分
     * @param impMaterial 待导物料
     * @return true/false
     */
    private List<MMaterialDictionary> getMaterialDictionary(String matType, ImportMaterialModel impMaterial) {
        MMaterialDictionary materialDictionary = new MMaterialDictionary();
        materialDictionary.setMdPid("板材".equals(impMaterial.getMaterialKind()) ? 1 : 2);// 分类
        // 类别（1000 类型、2000	材质、3000 规格）
        if ("类型".equals(matType)) {
            materialDictionary.setMdTypeNum(1000);
            materialDictionary.setMdName(impMaterial.getMatTypeName());
        } else if ("材质".equals(matType)) {
            materialDictionary.setMdTypeNum(2000);
            materialDictionary.setMdName(impMaterial.getMatQualityName());
        } else if ("规格".equals(matType)) {
            materialDictionary.setMdTypeNum(3000);
            materialDictionary.setMdName(impMaterial.getMatSpecName());
        }
        return mMaterialDictionaryDao.existMaterialDictionaryByQuery(materialDictionary);
    }

}
